package at.ac.tuwien.mg.wh.client;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.mg.bean.Item;
import at.ac.tuwien.mg.bean.Order;
import at.ac.tuwien.mg.wh.WarehouseBeanRemote;
import at.ac.tuwien.mg.wh.dto.DescribedItemDTO;
import at.ac.tuwien.mg.wh.dto.ItemDTO;
import at.ac.tuwien.mg.wh.exception.WarehouseException;

public abstract class Client implements JavaDelegate {

	private static Logger log = LoggerFactory.getLogger(Client.class);

	// protected InitialContext ctx;
	// protected WarehouseBeanRemote bean;

	@Override
	public void execute(DelegateExecution execution) throws Exception {

	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <I, C extends I> I lookupStateless(InitialContext ctx)
			throws NamingException {
		Hashtable jndiProperties = new Hashtable();
		jndiProperties.put(Context.URL_PKG_PREFIXES,
				"org.jboss.ejb.client.naming");
		ctx = new InitialContext(jndiProperties);
		return (I) ctx.lookup("ejb:/mg_warehouse/WarehouseBean!"
				+ WarehouseBeanRemote.class.getName());
	}

	public void closeContext(InitialContext ctx) {

		if (ctx != null) {
			try {
				ctx.close();
			} catch (NamingException e) {
			}
		}
	}

	public static Long toLong(String str) {
		return new Long(str);
	}

	public static void setDB(WarehouseBeanRemote bean)
			throws WarehouseException {
		List<DescribedItemDTO> list = new ArrayList<DescribedItemDTO>();
		list.add(new DescribedItemDTO(1L, 0, "silver", "", ""));
		list.add(new DescribedItemDTO(2L, 0, "wood", "", ""));
		list.add(new DescribedItemDTO(3L, 0, "gold", "", ""));
		list.add(new DescribedItemDTO(4L, 0, "stone", "", ""));

		bean.newItems(list);

		List<ItemDTO> list2 = new ArrayList<ItemDTO>();
		list2.add(new ItemDTO(1L, 10));
		list2.add(new ItemDTO(2L, 10));
		list2.add(new ItemDTO(3L, 10));
		list2.add(new ItemDTO(4L, 10));

		bean.addItems(list2);
	}

	public static void setInitBooked(WarehouseBeanRemote bean)
			throws WarehouseException {

		List<ItemDTO> list2 = new ArrayList<ItemDTO>();
		list2.add(new ItemDTO(4L, 7));
		bean.bookItems(list2, new Long(100));
	}

	public static List<ItemDTO> orderToItemList(Order order)
			throws WarehouseException {
		List<ItemDTO> input = new ArrayList<ItemDTO>();

		for (Item item : order.getOrder()) {
			input.add(new ItemDTO(ItemDTO.resolveItem(item.getGood()), item
					.getAmount()));
		}

		return input;
	}

	public static List<Long> itemListToIdList(List<ItemDTO> items) {
		List<Long> input = new ArrayList<Long>();
		for (ItemDTO i : items) {
			input.add(i.getCatalogId());
		}
		return input;
	}

	public static void log(String str) {
		// log.info(str);
		System.out.println(str);
	}

}
